package com.fishingwithme.domain;

import com.fishingwithme.infrastructure.dtos.circle.CityDto;
import com.fishingwithme.infrastructure.mapper.circle.CityMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private CityMapper cityMapper;

    @Override
    public List<CityDto> getAllCities() {
        return cityMapper.selectAllCities();
    }
    
    @Override
    public IPage<CityDto> getCitiesByPage(Integer pageNum, Integer pageSize) {
        // 验证参数，设置默认值
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        
        // 默认每页50条记录，符合需求中的limit 50
        if (pageSize == null || pageSize <= 0) {
            pageSize = 50;
        }
        
        Page<CityDto> page = new Page<>(pageNum, pageSize);
        return cityMapper.selectCitiesByPage(page);
    }
    
    @Override
    public IPage<CityDto> getCitiesByPageAndSearch(Integer pageNum, Integer pageSize, String cityName) {
        // 验证参数，设置默认值
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        
        // 默认每页50条记录，符合需求中的limit 50
        if (pageSize == null || pageSize <= 0) {
            pageSize = 50;
        }
        
        Page<CityDto> page = new Page<>(pageNum, pageSize);
        
        // 如果没有搜索关键词，返回普通分页结果
        if (cityName == null || cityName.trim().isEmpty()) {
            return cityMapper.selectCitiesByPage(page);
        }
        
        // 有搜索关键词时，执行带搜索的分页查询
        return cityMapper.selectCitiesByPageAndSearch(page, cityName.trim());
    }

    @Override
    public List<CityDto> searchCities(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getAllCities();
        }
        return cityMapper.searchCitiesByName(keyword.trim());
    }
    
    @Override
    @Transactional
    public boolean addCity(CityDto cityDto) {
        try {
            if (cityDto == null || cityDto.getCityCode() == null || cityDto.getCityCode().trim().isEmpty() ||
                    cityDto.getCity() == null || cityDto.getCity().trim().isEmpty()) {
                log.error("添加城市失败：参数不完整");
                return false;
            }
            
            // 使用INSERT IGNORE语法避免重复插入
            int result = cityMapper.insertCityIgnoreDuplicate(cityDto);
            
            // 如果result > 0，表示插入成功；如果result = 0，表示记录已存在但被忽略
            boolean success = result > 0;
            
            if (success) {
                log.info("成功添加城市：{}", cityDto.getCity());
            } else {
                log.info("城市已存在，忽略添加：{}", cityDto.getCity());
            }
            
            return success;
        } catch (Exception e) {
            log.error("添加城市失败", e);
            return false;
        }
    }

    @Transactional
    public void refreshCityData() {
        long startTime = System.currentTimeMillis();
        
        try {
            // 1. 预检查 - 查看是否有待处理的数据
            int pendingCount = cityMapper.countPendingCities();
            if (pendingCount == 0) {
                log.info("城市数据刷新完成 - 无新增数据需要处理");
                return;
            }
            
            log.info("开始城市数据刷新任务 - 待处理数据: {}条", pendingCount);
            
            // 2. 分批处理数据（每批1000条）
            int processedCount = 0;
            int batchCount = 0;
            
            while (processedCount < pendingCount) {
                List<CityDto> citiesFromSpot = cityMapper.selectDistinctCitiesFromSpot();
                
                if (citiesFromSpot.isEmpty()) {
                    break;
                }
                
                // 3. MySQL批量插入优化
                if (citiesFromSpot.size() > 1) {
                    // 批量插入（性能提升5-10倍）
                    int insertedCount = cityMapper.batchInsertCities(citiesFromSpot);
                    log.debug("批量插入完成 - 条数: {}, 实际插入: {}", citiesFromSpot.size(), insertedCount);
                } else {
                    // 单条插入兜底
                    cityMapper.insertCityIgnoreDuplicate(citiesFromSpot.get(0));
                }
                
                int batchSize = citiesFromSpot.size();
                processedCount += batchSize;
                batchCount++;
                
                log.debug("批量处理完成 - 批次: {}, 处理条数: {}, 累计处理: {}/{}",
                         batchCount, batchSize, processedCount, pendingCount);
                
                // 4. 内存优化 - 帮助垃圾回收
                citiesFromSpot.clear();
            }
            
            long endTime = System.currentTimeMillis();
            log.info("城市数据刷新任务完成 - 总处理: {}条, 耗时: {}ms, 批次: {}", 
                     processedCount, (endTime - startTime), batchCount);
            
        } catch (Exception e) {
            log.error("城市数据刷新任务执行失败", e);
            throw e;
        }
    }
}